﻿using ZenSystemService.Api.Services;
using ZenSystemService.Api.Entities;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.DTOs;
using System.Transactions;
using Microsoft.AspNetCore.Components.Forms;
using System.Collections.Generic;
using ZenSystemService.Api.Common.Encryption;
namespace ZenSystemService.Api.Business
{
    public class UserBusiness
    {
        private readonly UserService _userService;
        private readonly IEncryptionService _encryptionService;
        private readonly ZenBrightBusiness _zenBrightBusiness;
        public UserBusiness(UserService userService, IEncryptionService encryptionService, ZenBrightBusiness zenBrightBusiness)
        {
            _userService = userService;
            _encryptionService = encryptionService;
            _zenBrightBusiness = zenBrightBusiness;
        }

        /// <summary>
        /// 创建初始学员信息
        /// </summary>
        /// <param name="salesCreateUserRequest"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public  async Task<User> CreateInitialTrainee(CreateUserMainAccountDTO _createUserMainAccountDTO, int _coachId,int currentUserId)
        {
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                User _user = new User();
                _user.Username = _createUserMainAccountDTO.Mobile;
                _user.UserType = ((int)UserType.Trainee).ToString();
                _user.Mobile = _createUserMainAccountDTO.Mobile;
                _user.Enabled = "1";
                _user.LastLoginDate = DateTime.Now;
                _user.CreatedDate = DateTime.Now;
                _user.ParentUserId = 0;
                _user.RealName = _createUserMainAccountDTO.Name;
                if (_createUserMainAccountDTO.Birthday != null)
                {
                    _user.Birthday = Convert.ToDateTime(_createUserMainAccountDTO.Birthday);
                }
                _user.Gender = _createUserMainAccountDTO.Gender;
                _user.CoachId = _coachId;
                User currentUser = await _userService.GetUserByIdAsync(_coachId);
                _user.InstitutionId = currentUser.InstitutionId;
                string password = _user.Mobile.Substring(_user.Mobile.Length - 6);
                _user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(password);
                _user.EncryptedPassword = _encryptionService.Encrypt(password);
                bool isSuccess = await _userService.CreateUserAsync(_user);


                if (isSuccess)
                {
                    //人员数据推送 ZenBright 系统
                    ZenBrightCreateUserInfoRequest _zenBrightCreateUserInfoRequest = new ZenBrightCreateUserInfoRequest();
                    _zenBrightCreateUserInfoRequest.zenSystemUserId = _user.UserId;
                    _zenBrightCreateUserInfoRequest.userName = _user.Username;
                    _zenBrightCreateUserInfoRequest.password = password;
                    _zenBrightCreateUserInfoRequest.realName = _user.RealName;
                    _zenBrightCreateUserInfoRequest.gender = _user.Gender == null ? 0 : Convert.ToInt32(_user.Gender);
                    _zenBrightCreateUserInfoRequest.mobile = _user.Mobile;
                    _zenBrightCreateUserInfoRequest.birthday = _user.Birthday.HasValue ? _user.Birthday.Value.ToString("yyyy-MM-dd") : "";
                    _zenBrightCreateUserInfoRequest.remark = "";
                    bool pushZenBrightIsSuccess = await this.PushZenBrightUserInfo(_zenBrightCreateUserInfoRequest, currentUserId);
                    if (!pushZenBrightIsSuccess)
                    {
                        return null;
                    }
                    transScope.Complete();
                    return _user;
                }
                else
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 创建子账号
        /// </summary>
        /// <param name="_traineeCreateSubAccountRequest"></param>
        /// <returns></returns>
        public async Task<bool> CreateSubAccount(TraineeCreateSubAccountRequest _traineeCreateSubAccountRequest, int parentUserId,int currentUserId)
        {
            using (TransactionScope transScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                User ParentUser = await _userService.GetUserByIdAsync(parentUserId);

                User _user = new User();

                BaseBusiness.Instance.AutoMap(_traineeCreateSubAccountRequest, _user);
                _user.Enabled = "1";
                _user.UserType = ((int)UserType.Trainee).ToString();
                _user.LastLoginDate = DateTime.Now;
                _user.CreatedDate = DateTime.Now;
                _user.ParentUserId = parentUserId;
                if (_traineeCreateSubAccountRequest.Birthday != null)
                {
                    _user.Birthday = Convert.ToDateTime(_traineeCreateSubAccountRequest.Birthday);
                }

                List<User> SubUserList = await _userService.GetAlTraineeSubAccountList(parentUserId);
                int subAccountCount = SubUserList == null ? 0 : SubUserList.Count();
                //_user.Mobile = ParentUser.Mobile.ToString() + (subAccountCount + 1).ToString();
                _user.Mobile = ParentUser.Mobile.ToString();
                _user.Username= ParentUser.Mobile.ToString() + (subAccountCount + 1).ToString();
                User currentUser = await _userService.GetUserByIdAsync(parentUserId);
                _user.InstitutionId = currentUser.InstitutionId;
                _user.CoachId = currentUser.CoachId;

                string password = ParentUser.Mobile.Substring(_user.Mobile.Length - 6);
                _user.PasswordHash = BCrypt.Net.BCrypt.HashPassword(password);
                _user.EncryptedPassword = _encryptionService.Encrypt(password);

                bool createUserIsSuccess = await _userService.CreateUserAsync(_user);
                if (!createUserIsSuccess)
                {
                    return false;
                }

                //创建人物关系
                TraineeCharacterRelation traineeCharacterRelation = new TraineeCharacterRelation();
                traineeCharacterRelation.ParentAccountUserId = parentUserId;
                traineeCharacterRelation.SubAccountUserId = _user.UserId;
                traineeCharacterRelation.TraineeRelationId = _traineeCreateSubAccountRequest.TraineeRelationId;
                traineeCharacterRelation.Remark = _traineeCreateSubAccountRequest.TraineeRelationIRemark;
                bool saveRelationIsSuccess = await _userService.CreateTraineeCharacterRelationAsync(traineeCharacterRelation);
                if (saveRelationIsSuccess == false)
                {
                    return false;
                }
              

                
                //人员数据推送 ZenBright 系统
                ZenBrightCreateUserInfoRequest _zenBrightCreateUserInfoRequest = new ZenBrightCreateUserInfoRequest();
                _zenBrightCreateUserInfoRequest.zenSystemUserId = _user.UserId;
                _zenBrightCreateUserInfoRequest.userName = _user.Username;
                _zenBrightCreateUserInfoRequest.password = password;
                _zenBrightCreateUserInfoRequest.realName = _user.RealName;
                _zenBrightCreateUserInfoRequest.gender = _user.Gender == null ? 0 : Convert.ToInt32(_user.Gender);
                _zenBrightCreateUserInfoRequest.mobile = _user.Mobile;
                _zenBrightCreateUserInfoRequest.birthday = _user.Birthday.HasValue ? _user.Birthday.Value.ToString("yyyy-MM-dd") : "";
                _zenBrightCreateUserInfoRequest.remark = "";
                bool pushZenBrightIsSuccess =  await this.PushZenBrightUserInfo(_zenBrightCreateUserInfoRequest, currentUserId);
                if (!pushZenBrightIsSuccess)
                {
                    return false;
                }    
                transScope.Complete();
                return true;
            }
        }



        /// <summary>
        /// 推送 Bright 系统人员数据
        /// </summary>
        /// <param name="_zenBrightCreateUserInfoRequest"></param>
        /// <returns></returns>
        public async Task<bool> PushZenBrightUserInfo(ZenBrightCreateUserInfoRequest _zenBrightCreateUserInfoRequest, int currentUserId)
        {
            string msg;
            bool isSuccess;
            ZenBrightCreateUserInfoResponse zenBrightCreateUserInfoResponse = ApiUtility.RequestPostApi<ZenBrightCreateUserInfoResponse>("api/ZenSystem/CreateUserInfo", _zenBrightCreateUserInfoRequest, out isSuccess, out msg);
            if (isSuccess)
            {
                if (zenBrightCreateUserInfoResponse.Status)
                {
                    LegencyUserZenUser legencyUserZenUser = new LegencyUserZenUser();
                    legencyUserZenUser.LegencyUserId = zenBrightCreateUserInfoResponse.Data.HasValue ? zenBrightCreateUserInfoResponse.Data.Value : 0;
                    legencyUserZenUser.ZenUserId = _zenBrightCreateUserInfoRequest.zenSystemUserId;
                    bool saveIsSuccess = await _userService.CreateLegencyUserZenUser(legencyUserZenUser);

                    if (!saveIsSuccess)
                        return false;

                    //推送订单
                    bool sendTestOrderIsSuccess = await _zenBrightBusiness.SendDefaultTestOrder(legencyUserZenUser.LegencyUserId, legencyUserZenUser.ZenUserId, currentUserId);
                    return sendTestOrderIsSuccess;
                }
                else
                {
                    Console.WriteLine("插入Bright系统人员信息失败:" + zenBrightCreateUserInfoResponse.Message);
                    return false;
                }
            }
            else
            {
                Console.WriteLine("调用api/ZenSystem/CreateUserInfo接口失败:" + msg);
                return false;
            }
        }

        /// <summary>
        /// 修改 Bright 系统人员数据
        /// </summary>
        /// <param name="_zenBrightCreateUserInfoRequest"></param>
        /// <returns></returns>
        public async Task<bool> UpdateZenBrightUserInfo(ZenBrightCreateUserInfoRequest _zenBrightCreateUserInfoRequest)
        {
            string msg;
            bool isSuccess;
            ZenBrightCreateUserInfoResponse zenBrightCreateUserInfoResponse = ApiUtility.RequestPostApi<ZenBrightCreateUserInfoResponse>("api/ZenSystem/ModifyUserInfo", _zenBrightCreateUserInfoRequest, out isSuccess, out msg);
            if (isSuccess)
            {
                if (zenBrightCreateUserInfoResponse.Status)
                {
                   return true;
                }
                else
                {
                    Console.WriteLine("插入Bright系统人员信息失败:" + zenBrightCreateUserInfoResponse.Message);
                    return false;
                }
            }
            else
            {
                Console.WriteLine("调用api/ZenSystem/CreateUserInfo接口失败:" + msg);
                return false;
            }
        }



    }
}
